<?php

namespace app\index\controller;

use app\index\logic\LoginLogic;
use app\index\logic\SiteConfigLogic;
use app\index\model\CommentModel;
use app\index\model\MaterialModel;
use app\index\model\TagModel;
use app\index\util\Page;
use app\index\util\Response;
use Qiniu\Auth;
use think\Cache;
use think\Config;
use think\console\command\make\Model;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;

class BaseMessage extends Base
{
    protected $_model;
    protected $_img_model;
    protected $_comment_model;
    protected $_like_model;
    protected $_validate;
    protected $_template_add = '/base_message/add';
    protected $_template_detail = '/base_message/detail';
    protected $_template_index = '/base_message/index';
    protected $_template_comment = '/base_message/comment';
    protected $_template_ajax_list = '/base_message/ajax_list';
    protected $_template_comment_list = '/base_message/comment_list';
    protected $_template_ajax_comment_list = '/base_message/ajax_comment_list';
    protected $_size = 10;
    /**
     * 需要登录才能操作的
     * 添加页面，添加动作，更新动作
     * @var array
     */
    protected $_check_login = [
        'like','unlike','add', 'insert', 'update', 'comment', 'add_comment','my_list','delete'
    ];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $controller = Request::instance()->controller();
        $this->assign('title',get_module_name($controller));
    }

    /**
     * 输出列表页
     * @return \think\response\View
     */
    public function index()
    {
        $order = input('order','1','intval');
        $list = $this->_get_list($order,$this->_size,1);
        if($list['total'] <= $this->_size){
            $this->assign('list_end',1);
        }else{
            $this->assign('list_end',0);
        }
        $this->assign('list',$list['data']);
        $this->assign('order',$order);
        return view($this->_template_index);
    }

    /**
     * ajax获取列表
     */
    public function ajax_list(){
        $order = input('order','1','intval');
        $page = input('page','1','intval');
        $result = [];
        $data = $this->_get_list($order,$this->_size,$page);
        $this->assign('list',$data['data']);
        $result['page'] = $data['page'];
        $result['is_end'] = $data['is_end'];
        $content = $this->fetch($this->_template_ajax_list);
        $result['content'] = $content;
        Response::json(1,'加载成功',$result);
    }

    /**
     * 获取列表方式
     * @param $order
     * @param $size
     * @param $page
     * @return array
     */
    protected function _get_list($order,$size,$page){
        if($order == 1){
            $sql = 'SELECT * FROM '.$this->_model->getTable().' as m LEFT JOIN (SELECT count(id) as like_num,message_id FROM '.$this->_like_model->getTable().' GROUP by message_id ) as c  ON m.id = c.message_id where m.status = 1 GROUP BY m.id ORDER BY like_num desc';
            $list = Db::query($sql);
        }elseif($order == 2){
            $sql = 'SELECT count(c.id) as comment_num ,m.* FROM '.$this->_model->getTable().' as m LEFT JOIN  '.$this->_comment_model->getTable().' as c  ON m.id = c.message_id where m.status = 1 GROUP BY m.id ORDER BY m.update_time desc';
            $list = Db::query($sql);
        }else{
            $sql = 'SELECT count(c.id) as comment_num ,m.* FROM '.$this->_model->getTable().' as m LEFT JOIN  '.$this->_comment_model->getTable().' as c  ON m.id = c.message_id where m.status = 1 GROUP BY m.id ORDER BY m.pv desc';
            $list = Db::query($sql);
        }
        foreach ($list as &$value){
            $value['detail'] = cut_str($value['detail'],50);
        }
        return Page::return_page_data($list,$size,$page);
    }
    /**
     * 输出页面前动作
     */
    protected function _before_add()
    {

    }

    /**
     * 显示输出页面，输出七牛的token与domain
     */
    public function add()
    {
        $this->_before_add();
        $this->qiniu_start();
        return view($this->_template_add);
    }

    /**
     * 添加PV数
     * 需要验证seed，防止被刷
     */
    public function add_pv()
    {
        $id = input('id', 0, 'intval');
        $seed = input('seed', 0, 'htmlspecialchars');
        if ($seed == Session::get('pv_seed') && $id != 0) {
            $this->_model->where(['id' => $id])->setInc('pv');
        }
    }

    /**
     * 详情页
     * @return \think\response\View
     */
    public function detail()
    {
        $id = input('id', 0, 'intval');
        $detail = $this->_model->where(['id' => $id,'status'=>1])->find();
        if (!$detail) {
            $this->error('信息不存在');
        }
        $detail['like_num'] = $this->_get_like_num($id);
        $detail['comment_num'] = $this->_get_comment_num($id);
        $comment_list = $this->get_comment_list($id,5,1);
        $this->assign('comment_list',$comment_list['data']);
        $this->assign('is_like', $this->_get_like_status($id));
        $this->assign('vo', $detail);
        $seed = md5(time() . rand(1000, 9999));
        Session::set('pv_seed', $seed);
        $this->assign('seed', $seed);
        return view($this->_template_detail);
    }

    /**
     * 获取点赞数量
     * @param $id
     * @return int
     */
    protected function _get_like_num($id)
    {
        if ($this->_like_model) {
            return $this->_like_model->where(['message_id' => $id])->count();
        } else {
            return 0;
        }
    }

    /**
     * 获取评论数量
     * @param $id
     * @return int
     */
    protected function _get_comment_num($id)
    {
        if ($this->_comment_model) {
            return $this->_comment_model->where(['message_id' => $id])->count();
        } else {
            return 0;
        }
    }

    /**
     * 获取当前信息，用户是否点赞过
     * @param $id
     * @return int
     */
    protected function _get_like_status($id)
    {
        if (!$this->_like_model) {
            return 0;
        }
        $uid = $this->_user_id;
        if (!$uid) {
            return 0;
        }
        if ($this->_like_model->where(['uid' => $uid, 'message_id' => $id])->find()) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 点赞
     */
    public function like()
    {
        $uid = $this->_user_id;
        if (!$uid) {
            Response::json('-1', '请先登录');
        }
        $id = Request::instance()->request('id', 0, 'intval');
        $log = $this->_like_model->where(['message_id' => $id, 'uid' => $this->_user_id])->find();
        if ($log) {
            Response::json('-2', '您已经赞过了，请不要再赞');
        } else {
            $data = [];
            $data['message_id'] = $id;
            $data['uid'] = $uid;
            $this->_like_model->save($data);
            $data = [];
            $data['like_num'] = $this->_get_like_num($id);
            Response::json('1', '点赞成功！', $data);
        }
    }

    /**
     * 取消点赞
     */
    public function unlike()
    {
        $uid = $this->_user_id;
        if (!$uid) {
            Response::json('-1', '请先登录');
        }
        $id = Request::instance()->request('id', 0, 'intval');
        $log = $this->_like_model->where(['message_id' => $id, 'uid' => $this->_user_id])->find();
        if (!$log) {
            Response::json('-2', '你还没点赞过呢');
        } else {
            $where = [];
            $where['message_id'] = $id;
            $where['uid'] = $uid;
            $this->_like_model->where($where)->delete();
            $data = [];
            $data['like_num'] = $this->_get_like_num($id);
            Response::json('1', '取消点赞成功！', $data);
        }
    }

    /**
     * 获取评论列表
     * @param $id 信息ID
     * @param $size 每页数量
     * @param $page 第几页
     * @return array
     */
    public function get_comment_list($id,$size = 10,$page = 1)
    {
        $is_ajax = Request::instance()->isAjax();
        if($is_ajax){
            $page = input('page',1,'intval');
            $page = 1;
        }else{
            $result = [];
            $result['data'] = [];
            $result['total'] = 1;
        }
        if ($this->_comment_model) {
            $list = $this->_comment_model->where(['message_id' => $id])->order('update_time desc')->select();
            $data = Page::return_page_data($list,$size,$page);
            if(Request::instance()->isAjax()){
                if(ceil($data['total'] / $size) >= $page){
                    $result['is_end'] = 0;
                }else{
                    $result['is_end'] = 1;
                }
                $result['page'] = $page + 1;
                $this->assign('list',$data['data']);
                $content = $this->fetch($this->_template_ajax_comment_list);
                $result['content'] = $content;
                Response::json(1,'SUCCESS',$result);
            }else{
                $result = $data;
            }
        }
        return $result;
    }

    /**
     * 发表评论
     */
    public function comment()
    {
        $id = input('id', 0, 'intval');
        $model = new TagModel();
        $list = $model->order('sort')->select();
        $this->assign('list', $list);
        $this->assign('id', $id);
        return view($this->_template_comment);
    }

    /**
     * 添加评论
     */
    public function add_comment()
    {
        $id = input('id', 0, 'intval');
        $tag_ids = input('tag_ids', '', 'htmlspecialchars');
        $uid = $this->_user_id;
        if (!$uid) {
            Response::json(-2, '请先登录');
        }
        $tag_ids = explode(',', $tag_ids);
        $comment = '';
        $model = new TagModel();
        foreach ($tag_ids as $value) {
            $tag = $model->where(['id' => $value])->find();
            if ($tag) {
                $comment .= $tag['name'] . ',';
            }
        }
        if ($comment == '') {
            Response::json(-1, '评论不能为空');
        }
        $where = [];
        $where['message_id'] = $id;
        $where['uid'] = $this->_user_id;
        if ($this->_comment_model->where($where)->find()) {
            $data = [];
            $data['comment'] = rtrim($comment, ',');
            $this->_comment_model->save($data, $where);
        } else {
            $data = [];
            $data['message_id'] = $id;
            $data['uid'] = $this->_user_id;
            $data['comment'] = rtrim($comment, ',');
            $this->_comment_model->save($data);
        }
        Response::json(1, '评论成功！');
    }

    /**
     * 显示所有评论
     */
    public function comment_list(){
        $id = input('id',0,'intval');
        $list = $this->get_comment_list($id,10,1);
        if($list['total'] < 10){
            $this->assign('comment_end',1);
        }else{
            $this->assign('comment_end',0);
        }
        $this->assign('list',$list['data']);
        $this->assign('id',$id);
        return view($this->_template_comment_list);
    }

    /**
     * 删除
     */
    public function delete(){
        $id = input('id',0,'intval');
        $this->_model->where(['id'=>$id,'uid'=>$this->_user_id])->delete();
        Response::json(1);
    }


}